package net.lesscoding.server.handler;

import cn.hutool.core.util.StrUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import net.lesscoding.message.GroupJoinRequestMessage;
import net.lesscoding.message.GroupJoinResponseMessage;
import net.lesscoding.session.Group;
import net.lesscoding.session.GroupSession;
import net.lesscoding.session.SessionFactory;

import java.util.List;

/**
 * @author eleven
 * @date 2024/10/31 16:55
 * @apiNote
 */
@ChannelHandler.Sharable
public class GroupJoinRequestMessageHandler extends SimpleChannelInboundHandler<GroupJoinRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupJoinRequestMessage msg) throws Exception {
        String username = msg.getUsername();
        String groupName = msg.getGroupName();
        GroupSession groupSession = SessionFactory.groupSession();
        Group group = groupSession.getGroup(groupName);

        if (group == null) {
            ctx.writeAndFlush(new GroupJoinResponseMessage(false, groupName + "群聊不存在"));
        } else {
            ctx.writeAndFlush(new GroupJoinResponseMessage(true, StrUtil.format("{}加入群聊{}", username, groupName)));
            List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
            membersChannel.forEach(item -> item.writeAndFlush(new GroupJoinResponseMessage(true, StrUtil.format("{}加入群聊{}", username, groupName))));
        }
    }
}
